#! /usr/bin/env python

import os
import sys
import cgi
import urllib
import cgitb
import Cookie

cgitb.enable()

m5_db_path = os.path.join('/export/homeO3/pengfei', 'M5-EDGE', 'util', 'stats')
sys.path.append(m5_db_path)

import db
from db import *
from output import *
from info import *

int_dict = {'gzip_graphic':164, 'vpr_route':175, 'gcc_166':176,
        'mcf':181, 'crafty':186, 'parser_spec':197,
        'perlbmk_makerand':253, 'gap':254, 'vortex_2':255,
        'bzip2_program':256, 'twolf':300}

fp_dict = {'wupwise':168, 'swim':171, 'mgrid':172, 'applu':173,
        'mesa':177, 'art_110':179, 'equake':183, 'ammp':188,
        'apsi':301}

def loginPage():
    print '''<form action="m5stats.py" method="post" name="portal">
      <table align=center>
        <tr align=center> 
          <td colspan=2> <div align=center>Please enter your username and password</div></td>
        </tr>
        <tr> 
          <td align=center> <font>Username</font></td>
          <td><font> 
            <input maxlength="20" name="username" size="8">
            </font></td>
        </tr>
        <tr>
          <td align=center><font>Password</font></td>
          <td><font>
            <input maxlength="20" type="password" name="password"
            size="8">
            </font></td>
        </tr>
        <tr> 
          <th align=center> 
              <input name="portalsubmit" type="submit"
              value="Submit">
          </th>

          <th align=center>
              <input name="portalsubmit2" type="reset"
              value="Reset">
          </th>
        </tr>
      </table>
    '''

def head():
    print '''<html>
    <head>
    <title>M5-EDGE Statistics Scratch Pad
    </title>

    </head>
    <style>
    #content
    {
        padding: 10px 0px 10px 0px;
        width: 80%;
        margin: 0px 10% 0px 10%;
        font-size: medium;
        font-family: Verdana, Geneva, Arial, Sans-Serif;
    }
    #title
    {
        padding: 10px 10px 10px 10px;
        font-weight:bold;
        margin: 10px 0 30px 5%;
    }
    .post
    {
        padding: 5px;
        margin: 0px 0px 10px 5%;
        display: block;
    }
    .post .headitem
    {
        margin: 0px 0px 5px 5px;
        display:block;
    }
    .item
    {
        margin: 0px 0px 0px 5px;
        display: inline;
    }
    a
    {
        text-decoration:none;
        color:Navy;
    }
    a:hover
    {
        color:White;
        background-color:Navy;
    }
    </style>
    </head>
    <body>
    <div id='content'>
    <div id='title' align=center><h1>
    <a href='http://202.118.229.70/m5stats/m5stats.py'>
    M5-EDGE Statistics Scratch Pad</a></h1>
    For questions, please contact <a
    href='http://202.118.229.70/mediawiki/index.php/HmecWiki:%E8%8B%9F%E9%B9%8F%E9%A3%9E'>
    Gou Pengfei</a>
    </div>'''

def showdata(source, form):
    if not (form.has_key("benches")) or not (form.has_key("confs")) \
       or not (form.has_key("stat")):
        print "Waiting for input..."
    else:
        benches = []
        if type(form['benches']) is list:
            benches = form['benches']
        else:
            benches = [form['benches']]

        confs = []
        if type(form['confs']) is list:
            confs = form['confs']
        else:
            confs = [form['confs']]

        db_stat = source.getStat(form['stat'].value)
        for i,db_s in enumerate(db_stat):

            print '-------%s--------' % db_s.name

            dist_data = None
            if db_s.type != 'DIST' and db_s.type != 'VECTORDIST':
                print '%-10s\t\t\t\t%-20s\t\t\t\t%-15s' % ('Bench', 'Configuration', 'Data')  
            else:
                dist_data = source.data(db_s)

            name = None
            conf = None
            bench = None

            for c in confs: 

                conf = c.value

                for b in benches:

                    bench = (b.value).split('_')
                    run_name = b.value + '-' + conf

                    if db_s.type == 'DIST' or db_s.type == 'VECTORDIST':

                        print '--------%s -- %s--------' % (bench[0], conf)

                        db_run = source.allRunNames[run_name]

                        if not dist_data.__contains__(db_run.run):
                            print 'Not exist'
                            continue

                        vec_size = len(dist_data[db_run.run][0])
                        for k in range(vec_size):
                            data_vector = []
                            for d in dist_data[db_run.run][0:db_s.size]:
                                data_vector.append(d[k])

                            print '----%s.%d----' % (db_s.name, k)

                            full_dist = FullDist(dist_data[db_run.run][-1][k],
                                                 dist_data[db_run.run][-2][k],
                                                 dist_data[db_run.run][-3][k],
                                                 dist_data[db_run.run][-4][k],
                                                 dist_data[db_run.run][-5][k],
                                                 dist_data[db_run.run][-6][k],
                                                 data_vector,
                                                 dist_data[db_run.run][-7][k],
                                                 db_s.min, db_s.max, db_s.bktsize,
                                                 db_s.size)

                            full_dist.display(db_s.name, db_s.desc,
                                              db_s.flags,db_s.precision)

                    else:
                        v = source.get(run_name, db_s)

                        if v == None:
                            print '%-10s\t\t\t\t%-20s\t\t\t\t%-15s' % (bench[0],\
                                    conf, 'Not exist')
                            continue

                        if type(v) is list:
                            for count, v_d in enumerate(v):
                                print '%-10s\t\t\t\t%-20s\t\t\t\t%-15f' % (bench[0],\
                                        conf + '-' + str(count), v_d)
                        else:
                            print '%-10s\t\t\t\t%-20s\t\t\t\t%-15f' % (bench[0],\
                                    conf, v)
def sortDict(container, keys):

    temp = [(container[k], k) for k in keys]

    temp.sort()

    return [k for v, k in temp]


if __name__ == '__main__':

    form = cgi.FieldStorage()
    source = db.Database()

    # Set the cookies
    if form.has_key("username") and form.has_key("password"):

        mycookie = Cookie.SimpleCookie()

        mycookie["M5StatsPassword"] = form["password"].value
        mycookie["M5StatsUserID"] = form["username"].value

        print mycookie

    print "Content-type: text/html\n\n"

    #Print head
    head()

    user_id = None
    pass_word = None

    if os.environ.has_key('HTTP_COOKIE'):
        mycookie = Cookie.SimpleCookie()

        mycookie.load(os.environ['HTTP_COOKIE'])

        if mycookie.has_key("M5StatsUserID") and \
            mycookie.has_key("M5StatsPassword"):

            user_id = mycookie["M5StatsUserID"].value

            pass_word = mycookie["M5StatsPassword"].value

    if user_id != None and pass_word != None:

        source.host = 'localhost'
        source.db = user_id
        source.user = user_id
        source.passwd = pass_word

        # Try to connect the database
        try:
            source.connect()
            print '''</fieldset></div><hr /><br /><div class='post'>
            <form method="post" action="m5stats.py" name="maintable">
            <fieldset>
            <table align=center>
            <tr>
                <th align=center>
                <input name="submit" value="ShowData" type="submit">
                </th>
                <th align=center>
                <input name="reset" value="Reset" type="reset">
                </th>
            </tr>
            </table>
            </fieldset>

            <fieldset>
              <table align=center>
                <thead align=center>
                  <tr align=center>
                    <th>Available Benchmarks</th>
                    <th>Available Configurations</th>
                    <th>Available Statitics</th>
                  </tr>
                </thead>
                <tbody>
                  <tr align=center>
            '''
            int_benches = {}
            fp_benches = {}
            confs = []
            for run in source.allRuns:
                (bench, conf) = (run.name).split('-')

                if int_dict.has_key(bench):
                    int_benches[bench] = int_dict[bench]
                elif fp_dict.has_key(bench):
                    fp_benches[bench] = fp_dict[bench]

                if not conf in confs:
                    confs.append(conf)

            # Sort the benchmarks according to their id
            int_list = sortDict(int_benches, int_benches.keys())
            fp_list = sortDict(fp_benches, fp_benches.keys())
            confs.sort()

            print '''
                    <td><select name="benches" size="10" multiple>
            '''

            for bench in int_list: 
                print '<option> %s' % bench

            for bench in fp_list:
                print '<option> %s' % bench

            print '''
                    </select></td>
                    <td><select name="confs" size="10" multiple>
            '''

            for conf in confs: 
                print '<option> %s' % conf

            print '''
                    </select></td>
                    <td><select name="stat" size="10">
            '''

            excluded = '__Stat'
            stats = [ stat.name for stat in source.allStats ]
            stats.sort(statcmp)
            for stat in stats:
                stat = source.allStatNames[stat]
                sname = stat.name
#                if sname[0:2] != '__':
#                    print '<option> %s' % stat.name
                print '<option> %s' % stat.name

            print '''
                    </select></td>
                    </tr>
                    </tbody>
                    </table>
                    <table align=center>
                    <thead>
                    <tr> <th>Data</th> </tr>
                    </thead>
                    <tr align=center>
                    <td align=center><textarea rows=40 cols=80 align=center>
            '''

            showdata(source, form)

            print '''
                  </textarea></td>
                  </tr>
              </table>
              </fieldset>
            </form></div>'''

        except:
            print '''
            <hr /><div class='post' align=center><div
            class='item'><b><font color=red><br>
            What are you doing here?</font></b></div>
            '''
            loginPage()

    else:
        loginPage()

    # Tail
    print '''</div><hr /><div class='post' align=center><div
    class='item'>Powered by Gou Pengfei</div></div>
    </div>
    </body>
    </html>'''
